package com.hui.auth.service.impl;

import com.hui.auth.dao.AuthMenuDao;
import com.hui.auth.dao.AuthPermissionDao;
import com.hui.auth.dao.AuthRoleDao;
import com.hui.auth.entity.AuthMenu;
import com.hui.auth.entity.AuthPermission;
import com.hui.auth.entity.AuthRole;
import com.hui.auth.service.AuthRoleService;
import com.hui.utils.ObjAnalysisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AuthRoleServiceImpl implements AuthRoleService {
    @Autowired
    private AuthRoleDao authRoleDao;
    @Autowired
    private AuthMenuDao menuDao;
    @Autowired
    private AuthPermissionDao permissionDao;

    @Override
    public boolean insert(AuthRole role) {
        if (authRoleDao.insert(role)) {
            return true;
        }
        return false;
    }

    @Override
    public List<AuthRole> selectAll(Map params) {
        return authRoleDao.selectAll(params);
    }

    @Override
    public boolean update(AuthRole role, List<Integer> menus, List<Integer> perms) {
        if (1 == authRoleDao.update(role)) {
            if (menus.size() > 0) {
                menuDao.deleteByRid(role.getId());
                menuDao.insertRoleMenu(role.getId(), menus);
            }
            if (perms.size() > 0) {
                permissionDao.deleteByRid(role.getId());
                permissionDao.insertRolePerms(role.getId(), perms);
            }
            return true;
        }
        return false;
    }

    @Override
    public boolean delete(Integer id) {
        authRoleDao.deleteRoleMenu(id);
        authRoleDao.deleteRolePerm(id);
        if (1 == authRoleDao.delete(id)) {
            return true;
        }
        return false;
    }

    @Override
    public Map<String, Object> select(Long rid) throws Exception {
        Map<String, Object> result = new HashMap();
        Map<String, Object> role = ObjAnalysisUtil.convertBean(authRoleDao.select(rid));
        result.put("role", role);
        if (null != role) {
            result.put("menu", menuDao.selectIdListByRoleId(rid));//菜单查询
            result.put("permission", permissionDao.selectByRid(rid));//权限查询
        }
        return result;
    }
}
